/*
 * Author: vyouzhi <vyouzhi@163.com>
 * http://www.xda.cn
 *
 * File: client_lib.c
 * Create Date: 2011-07-11 10:05:45
 *
 */
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include "client_lib.h"


struct sockaddr_in to_server_addr;
int server_fd;

int client_init(char *host, int port){
	int flag = 1;
    if((server_fd = socket(AF_INET , SOCK_STREAM , 0)) == - 1) {
        perror("socket error") ;
        return (-1);
    }

    memset(&to_server_addr, 0, sizeof(struct sockaddr)) ;
    to_server_addr.sin_family = AF_INET;
    to_server_addr.sin_port = htons(port);
    to_server_addr.sin_addr.s_addr = inet_addr(host) ;

	if (setsockopt(server_fd, IPPROTO_TCP, TCP_NODELAY,
                  &flag, sizeof(flag)) == -1) {
    	perror("Failed to set TCP_NODELAY");
    }
	if(connect(server_fd, (struct sockaddr *)&to_server_addr, sizeof(struct sockaddr)) == - 1) {
        perror("connect error") ;
        return (-1);
    }
	return (0);
}

int client_send(const char *sendData, int sendLen){
	const char *sd;
	int len;

	sd = sendData;
	len = sendLen;

	if(send(server_fd, sd, len, 0) == - 1) {
    	printf("client_lib send error line in 55 \n") ;
    	return (-1);
    }
	if(errno == EINTR)
		return (-1);
	if(errno == EAGAIN)
	{
		return (-1);
	}

	return (0);
}

int client_recv(char **recvBuf){
	char clientBuf[MAXDATASIZE];
	int nread, offset, stop;
	
	offset = stop = 0;
	bzero(clientBuf, MAXDATASIZE);

	do {
		nread = recv(server_fd, clientBuf + offset, MAXDATASIZE - offset, 0);
		if (nread == -1){
			if (errno != EINTR)
				return (-1);
		}
		else{
			if(memchr(clientBuf+offset, '\r', nread) != 0) stop = 1;
			offset += nread;
		}
	}while(offset < MAXDATASIZE && !stop);
	*recvBuf = clientBuf;

	return offset;
}

void client_close(void){
	
	close(server_fd);
}
/* vim: set ts=4 sw=4: */

